const app = getApp()
const util = require('../../utils/util.js')
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;

Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    theme: app.globalData.theme, //全局颜色变量
    config: app.globalData.config,
    // 1充值开启
    balanceIsEntrance: app.globalData.balanceIsEntrance,
    // 地址信息
    addressComponent: {
      city: null,
      title: null,
      address: null,
      longitude: null,
      latitude: null
    },
    scale: 15, //缩放级别，取值范围为5-18
    markers: [],
    noticeData: [],
    goodsListHot: [],
    // 默认服务
    goodsSpu: {}
  },
  onLoad(options) {
    qqmapsdk = new QQMapWX({
      key: 'UVQBZ-PNY63-AZW32-35VCS-GC7VZ-EBFD3' //这里自己的key秘钥进行填充
    });
    // 保存别人分享来的 userCode
    util.saveSharerUserCode(options);
    app.initPage()
      .then(res => {
        this.loadData();
        this.setData({
          balanceIsEntrance: app.globalData.balanceIsEntrance
        });
      })
  },
  onShow() {},
  loadData() {
    this.loadLocation()
    this.noticeGet()
  },
  // 获取经纬度
  loadLocation: function () {
    const _this = this;
    app.checkLocation().then(function (res) {
      app.getCurrentLocation().then(function (res) {
        _this.loadAddress(res.longitude, res.latitude);
      }).catch(function (error) {
        console.log(error);
        _this.loading = false;
        wx.showToast({
          title: "获取位置信息失败，请检查是否打开位置权限",
          icon: 'none',
          duration: 2000
        });
      });
    });
  },
  // 获取当前地理位置
  loadAddress: function (longitude, latitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      sig: 'qXTQVZNXyPfofQD5Ty2RirEUIYjC5z', // 必填
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let result = res.result;
        // console.log(JSON.stringify(res));
        let city = result.address_component.city
        let title = result.formatted_addresses.recommend
        let address = result.address
        console.log("地址：" + address)
        let addressComponent = {
          city: city,
          title: title,
          address: address,
          longitude: longitude,
          latitude: latitude
        }

        app.globalData.addressComponent = addressComponent
        vm.setData({
          addressComponent: addressComponent
        });
        // 加载服务列表
        vm.goodsHot()
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  toMapPage() {
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=UVQBZ-PNY63-AZW32-35VCS-GC7VZ-EBFD3&referer=这里修车`
    });
  },
  // 视野发生变化时触发 获取中心点（即用户选择的位置）
  regionchange(e) {
    if (e.type == "end" && e.causedBy == "drag") {
      this.getCenterLngLat();
    }
  },
  //点击标记时触发
  markertap: function (e) {
    //标记id
    let that = this;
    let markerId = e.markerId;
    console.log('标记', markerId, e)
  },
  // 定位函数，将地图中心移动到当前定位点
  toPosition: function () {
    this.mapCtx.moveToLocation();
  },
  //获取中心点经纬度
  getCenterLngLat: function () {
    let that = this;
    that.mapCtx = wx.createMapContext('map');
    that.mapCtx.getCenterLocation({
      success: function (res) {
        that.loadAddress(res.longitude, res.latitude)
      }
    })
  },
  handleContact() {
    wx.makePhoneCall({
      phoneNumber: '4008888888'
    })
  },
  //热门维修
  goodsHot() {
    app.api.goodsPage({
        searchCount: false,
        current: 1,
        size: 6,
        descs: 'sale_num',
        city: this.data.addressComponent.city
      })
      .then(res => {
        let goodsListHot = res.data.records || []
        this.setData({
          goodsListHot: goodsListHot
        })
        if(goodsListHot.length > 0){
          this.goodsGet(goodsListHot[0].id)
        }
      })
  },
  //获取广告通知
  noticeGet() {
    app.api.noticeGet({
        type: '2',
        enable: '1'
      })
      .then(res => {
        let notice = res.data
        if (notice) {
          this.setData({
            noticeData: notice.listNoticeItem
          })
        }
      })
  },
  // 查询默认服务详情
  goodsGet(id) {
    app.api.goodsGet(id)
        .then(res => {
          let goodsSpu = res.data
          this.setData({
            goodsSpu: goodsSpu
          })
        })
  },
  // 一键下单
  handleOrder() {
    if(this.data.goodsListHot.length > 0){
      let goodsSpu = this.data.goodsSpu
      let goodsSku = this.data.goodsSpu.skus[0]
      let specInfo = ''
      // let goodsSpecData = this.data.goodsSpecData
      // goodsSpecData.forEach(function (spec, index) {
      //   spec.leaf.forEach(function (specItem) {
      //     if (spec.checked == specItem.id) {
      //       specInfo = specInfo + specItem.value
      //       if (goodsSpecData.length != index + 1) {
      //         specInfo = specInfo + ';'
      //       }
      //     }
      //   })
      // })
      /* 把参数信息异步存储到缓存当中 */
      wx.setStorage({
        key: 'param-orderConfirm',
        data: [{
          spuId: goodsSpu.id,
          skuId: goodsSku.id,
          quantity: 1,
          salesPrice: goodsSku.salesPrice,
          spuName: goodsSpu.name,
          sellPoint: goodsSpu.sellPoint,
          specInfo: specInfo,
          picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
          pointsDeductSwitch: goodsSpu.pointsDeductSwitch,
          pointsDeductScale: goodsSpu.pointsDeductScale,
          pointsDeductAmount: goodsSpu.pointsDeductAmount,
          pointsGiveSwitch: goodsSpu.pointsGiveSwitch,
          pointsGiveNum: goodsSpu.pointsGiveNum,
          freightTemplat: goodsSpu.freightTemplat,
          weight: goodsSku.weight,
          volume: goodsSku.volume,
          deliveryPlace: goodsSpu.deliveryPlace
        }]
      })
      wx.navigateTo({
        url: '/pages/order/order-confirm/index'
      })
    }
  }
})